<?php
namespace App\Http\Controllers\AppApi\Order;

use App\admin\Service\OA;
use App\Http\Controllers\AppApi\BaseController as Controller;
use App\Jobs\Fun;
use App\Models\Admin\CategoryModel;
use App\Models\Admin\OrderBaleModel;
use App\Models\Admin\OrderTempModel;
use App\Models\AreaModel;
use App\Models\CompanysModel;
use App\Models\User\UserLevelModel;
use App\Models\User\UserModel;
use App\Repositories\Admin\OrderBaleRepository;
use App\Services\Admin\OrderBaleService;
use App\Services\Api\UserLevel;
use App\Services\OrdersPayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class BaleController extends Controller
{
    /**
     * 货单
     * 制作者：九哥
     */

    protected $bale;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->bale = new OrderBaleService();
        $this->orderBaleRepository = new OrderBaleRepository();
        if (!$request->token) {
            return $this->returnJson(-2,'参数错误');
        }
        $this->uid = $this->accessGet($request->token);
        if(!$this->uid){
            return $this->returnJson(-13,'您未登录或未注册');
        }
        $type = UserModel::where('id',$this->uid)->value('type');
        if(!in_array($type,[2,3,4])){
            return $this->returnJson(-97,'您没有权限查看此目录');
        }
    }

    /**
     * 货单分类
     * /api/order/bale/cate
     */
    public function getCateList()
    {
        $dataArr = Cache::remember('api_order_balecate', 10000, function() {
            $models = $this->bale->getCateList();
            if (!count($models)) {
                return $this->toJson(-3);
            }
            return $models;
        });
        return $this->toJson(0,$dataArr);
    }

    /**
     * 货单列表
     * /api/order/bale/list
     */
    public function getBaleList(Request $request)
    {

        $cateId = $request->cateId ? $request->cateId : 0;
        $pageSize = 20;
        $page = intval($request->input('page',1));

        $dataArr = Cache::remember('balegetBaleList'.$cateId.'_'.$page, 10, function()use($cateId,$page,$pageSize) {
                $offset = ($page - 1) * $pageSize;
                //var_dump($cateId,$offset,$pageSize);exit;
                $models = $this->bale->getOrderBaleByCid($cateId,$offset,$pageSize);
                if (!count($models)) { return $this->toJson(-3); }
                $dataArr = $models;
                return $dataArr;
        });

        return $this->toJson(0,$dataArr);
    }

    /**
     * 货单详情
     * @param Request $request
     * /api/order/bale/detail
     * @return array
     */
    public function categoryOrdersDetail(Request $request)
    {
       /// exit('fdsagdsa');
        $data = [];
        $id = intval($request->input('id',0));
        if(!$id){
            return $this->toJSON(-2);
        }

        $result = \Illuminate\Support\Facades\Cache::remember('/api/order/bale/detail'.$id, 1, function()use($id) {
            $result = $this->orderBaleRepository->getCategoryOrdersDetail($id);
            if (!$result) {
                return false;
            }
            return $result->toArray();
        });
        if(!$request){
            return $this->toJSON(-3);
        }

        $data['num'] = $result['num'];
        $data['scence'] = $result['scence'];
        $data['money'] = '¥'.$result['money'].'元';

        $data['material'] = $result['material'];
        $data['img'] =Fun::pImg($result['img']);
        $data['imgDetails']=$result['imgDetails'];
        $data['detail'] = $result['detail'];
        $data['bond'] = $result['bond'];
        $data['is_rob'] = $result['is_rob'];
        //查询抢单数
        $count = OrderTempModel::where(['bale'=>$id])->count();
        $data['grapCount'] = $count;
        $data['status'] =OrderBaleModel::getStatus($result['status']);
        $data['period'] =Fun::date($result['period'],false);
        $data['ismy']=$result['uid']==OA::$user->getId();


        $data['name'] = $result['name'];
        $data['styleNo'] = $result['styleNo'];
        $data['styleName'] = $result['styleName'];
        $data['num'] = $result['num'];

        $data['scence'] = $result['scence'];
        $data['material'] = $result['material'];
        $data['tech'] = $result['tech'];
        $data['sizelist'] = $result['sizelist'];
        $data['costlist'] = $result['costlist'];

        $data['proType'] =OrderBaleModel::getproType($result['proType']);

        $data['region'] = AreaModel::getMergerName($result['region']);
        $data['proWay'] =OrderBaleModel::getproWay($result['proWay']);
        $data['outTypeStr'] =implode(',',CategoryModel::getNames(
            explode(",",$result['outTypeStr'])
        ));


        $data['stuff'] = $result['stuff'];
        $data['deplete'] = $result['deplete'];
        $data['orderType'] = $result['orderType'];

        $data['style'] = $result['style'];
        $data['design'] = $result['design'];
        $data['is_fabric'] = $result['is_fabric'];
        $data['cate'] =CategoryModel::getName($result['cate']);

        return $this->toJSON(0,$data);
    }


















    /**
     * 抢单详情  生成订单
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     * /api/order/bale/grapdetail
     * @deprecated
     */
    public function grapDetail(Request $request)
    {


        $id = intval($request->input('id',0));
        if(!$id){
            return $this->toJSON(-2);
        }
        $dataArr = [];
        if(!$this->uid){
            return $this->toJSON(-13);
        }

        $result = $this->orderBaleRepository->getCategoryOrdersDetail($id);
        if(!$result){
            return $this->toJSON(-3);
        }

        ///$dataArr['orderStatus']=$orderStatus;
        $dataArr['img'] =Fun::pImg($result['img']);
        $dataArr['detail'] = $result['detail'];
        $dataArr['num'] = $result['num'];
        $dataArr['money'] = $result['money'];
      //  $dataArr['allmoney'] = $result['money'] * $result['num'];
        //增补属性
        $dataArr['createTime'] = date('Y-m-d',$result['created_at']);
        $dataArr['orderNo'] = $result['order_no'] ?? '';
        $dataArr['orderTypeName'] = '工厂自己运输';


        //抢单工厂信息
        $factory = CompanysModel::where('uid',$this->uid)->first(['com_name','com_tel','com_address']);
       // var_dump($this->uid,$factory);exit;
        if(!$factory){
            return $this->returnJson(-97,'请先完善您的基本资料');
        }
        $dataArr['factory'] = $factory;

        return $this->toJSON(0,$dataArr);
    }


    /**
     * 抢单详情  生成订单
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     * /api/order/bale/grapdetail
     *
     * /api/order/bale/grapdetail2
     */
    public function grapDetail2(Request $request)
    {


        $id=intval($request->input('id',0));
        if(!$id){
            return $this->toJSON(-2);
        }
        $dataArr = [];
        if(!$this->uid){
            return $this->toJSON(-13);
        }

        $result = $this->orderBaleRepository->getCategoryOrdersDetail($id);
        if(!$result){
            return $this->toJSON(-3);
        }

        ///$dataArr['orderStatus']=$orderStatus;
        $dataArr['img'] =Fun::pImg($result['img']);
        $dataArr['detail'] = $result['detail'];
        $dataArr['num'] = $result['num'];
        $dataArr['money'] = $result['money'];
        $dataArr['bond'] = $result['bond'];
        $dataArr['is_rob'] = $result['is_rob'];
        //  $dataArr['allmoney'] = $result['money'] * $result['num'];
        //增补属性
        $dataArr['createTime'] = date('Y-m-d',$result['created_at']);
        $dataArr['orderNo'] = $result['order_no'] ?? '';
        $dataArr['orderTypeName'] = '工厂自己运输';
        $dataArr['notes'] = '';///Fun::encode($orderTemp['notes']);
        if($request['is_rob']==OrderBaleModel::is_rob_putong&&$result['bond']!=0){
            return $this->returnJson(-2,'订单错误,请和管理员联系');
        }

        //抢单工厂信息
        $factory = CompanysModel::where('uid',$this->uid)->first(['com_name','com_tel','com_address']);
        // var_dump($this->uid,$factory);exit;
        if(!$factory){
            return $this->returnJson(-97,'请先完善您的基本资料');
        }
        $dataArr['factory'] = $factory;

        return $this->toJSON(0,$dataArr);
    }






    /**
     * 确认抢单
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     * /api/order/bale/confirm-graporder
     */
    public function confirmGrapOrder(Request $request)
    {
        $id = intval($request->input('id',0));
        if(!$id){
            return $this->output([],'参数错误',-2);
        }

        $result = $this->orderBaleRepository->getCategoryOrdersDetail($id);
        if(!$result){
            return $this->output([],'没有数据',-3);
        }
        if($result['uid'] == $this->uid){
            return $this->output([],'不能抢自己的单子',-21);
        }
        if($result['del'] == 1){
            return $this->output([],'货单不存在',-21);
        }
        if($result['status'] == 1){
            return $this->output([],'该订单还未开始抢单',-100);
        }
        if($result['status'] == 3){
            return $this->output([],'该订单已经完成抢单了',-100);
        }
        if($status = intval(OrderTempModel::where(['bale'=>$id,'fid'=>$this->uid])->value('status'))){
            if($status == 3){
                return $this->output([],'您已经在抢单中了',-100);
            }
            if($status == 1){
                return $this->output([],'请先支付保证金',-200);
            }
            if($status >= 4){
                return $this->output([],'抢单已结束',-100);
            }
        }else{
            return $this->output([],'请先支付保证金',-200);
        }

        $data['status'] = 3;
        $data['updated_at'] = time();
        if(OrderTempModel::where(['bale'=>$id,'fid'=>$this->uid])->update($data)){
            return $this->output([],'抢单成功',0);
        }else{
            return $this->output([],'操作失败',-100);
        }
    }

    /**
     * 确认抢单
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function payorder(Request $request)
    {
        $id = intval($request->input('id',0));
        if(!$id){
            return $this->output([],'参数错误',-2);
        }

        $result = $this->orderBaleRepository->getCategoryOrdersDetail($id);
        if(!$result){
            return $this->output([],'没有数据',-3);
        }
        if($result['uid'] == $this->uid){
            return $this->output([],'不能抢自己的单子',-21);
        }
        if($result['del'] == 1){
            return $this->output([],'货单不存在',-21);
        }
        if($result['status'] == 1){
            return $this->output([],'该订单还未开始抢单',-100);
        }
        if($result['status'] == 3){
            return $this->output([],'该订单已经完成抢单了',-100);
        }
        if($status = intval(OrderTempModel::where(['bale'=>$id,'fid'=>$this->uid])->value('status'))){
            if($status == 3){
                return $this->output([],'您已经在抢单中了',-100);
            }
            if($status == 1){
                return $this->output([],'请先支付保证金',0);
            }
            if($status >= 4){
                return $this->output([],'抢单已结束',-100);
            }
        }else{
            return $this->output([],'请先支付保证金',0);
        }
    }

    /**
     * 抢单支付保证金
     *    type 1 支付宝 2微信 3银行卡
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     ** /api/order/bale/pay-grap
     */
    public function payGrap(Request $request)
    {
        return $this->output([], '接口弃用', 500);

        $channel = strtolower($request->input('channel', 'm'));
        $oid = intval($request->input('oid', 0));
        $type = intval($request->input('type', 1));
       // var_dump($channel,$oid,$type);  exit('sfds');
        //检查订单信息
        $orderBale = OrderBaleModel::where('id',$oid)->first();
        $orderStatus = $this->orderCheck($orderBale,$oid,$this->uid);
      ///  var_dump($channel,$oid,$type);exit;
        if($orderStatus['status']){
            try {
                if($type == 1){
                    //----------------------------------------------------支付宝参数-------------------------------------------------//
                    $bank = $request->input('bank', '');
                    $payMode = $request->input('payMode', 'directpay');
                    $returnUrl = route('pay.alipay.success');
                    $notifyUrl = route('pay.alipay.notify');
                    $subject = str_replace('&#8226;', '·', $orderBale['name']);
                    $out_trade_no = date('Ymdhms') . mt_rand(1000, 9999);
                    //----------------------------------------------------支付宝参数-------------------------------------------------//

                    $params['returnUrl'] = $returnUrl;
                    $params['notifyUrl'] = $notifyUrl;
                    $params['subject'] = $subject;
                    $params['out_trade_no'] = $out_trade_no;
                    $params['bank'] = $bank;
                    $params['oid'] = $oid;
                    $params['money'] = ($orderBale['num'] * $orderBale['money']) * 0.3;
                    $params['body'] = '抢单保证金';
                    if($params['money']<=0.01){
                        $params['money']=0.01;
                    }/*
                    $test=0.01001+0.00499;
                    $test=round($test,2);
                    var_dump($test);exit;*/
                 //   var_dump(route('pay.alipay.success'));exit;
                    $params['money']=$params['money']+0.00499;
                    $params['money']=round($params['money'],2);

                  //  var_dump($params['money']);exit;
                    $orderPayService = new OrdersPayService();
                    $result = $orderPayService->createaAipayTrade($channel,$payMode,$params);
                    if ($result === false) {
                        return $this->output([], '交易订单创建失败', 500);
                    }

                    if($this->orderTempAdd([
                        'bale'=>$oid,
                        'cid'=>$orderBale['uid'],
                        'fid'=>$this->uid,
                        'out_trade_no'=>$out_trade_no,
                        'status'=>OrderTempModel::status_weizhifu,
                        'created_at'=>time(),
                        'updated_at'=>time(),
                        'money'=>$params['money']
                    ])){
                        return $this->output($result, 'success', 200);
                        //return redirect($result);
                    }else{
                        return $this->output([], '抢单失败', 500);
                    }

                }elseif($type == 2){
                    return $this->output([], '待接入', 500);

                }elseif ($type == 3){
                    return $this->output([], '待接入', 500);

                }else{
                    return $this->output([], '支付方式错误', 500);
                }

            } catch (\Exception $exception) {
                return $this->output([], $exception->getMessage(), 500);
            }

        }else{
            return $this->output([], $orderStatus['msg'], 500);
        }
    }

    /**
     * 抢单订单信息检查
     * @param $oid
     */
    private function orderCheck($orderBale,$oid,$uid)
    {
        //查询订单信息
        if(!$orderBale){
            info('pay-error:订单信息不存在--订单id:'.$oid);
            return ['status'=>false,'msg'=>'订单信息不存在'];
        }
        if($orderBale['status'] !=2){
            info('pay-error:订单不在抢单时间范围--订单id:'.$oid);
            return ['status'=>false,'msg'=>'订单不在抢单时间范围'];
        }
        //查询用户抢单信息
        $orderTemp = OrderTempModel::where(['bale'=>$oid,'fid'=>$uid])->first();
        if(!$orderTemp){
            return ['status'=>true,'msg'=>''];
        }
        if($orderTemp['status'] != 1){
            info('pay-error:该订单已支付过或者已完成--订单id:'.$oid);
            return ['status'=>false,'msg'=>'该订单已支付过或者已完成'];
        }
        return ['status'=>true,'msg'=>''];
    }

    /**
     * 插入抢单信息表
     * @param $oid
     */
    private function orderTempAdd($data=[])
    {
        if(!$data){
            return false;
        }
        $newOrder=new OrderTempModel();
        $newOrder->bale=$data['bale'];
        $newOrder->fid=$data['fid'];
        $newOrder->cid=$data['cid'];
        $newOrder->status=$data['status'];
        $newOrder->out_trade_no=$data['out_trade_no'];
        $newOrder->created_at=time();
        $newOrder->updated_at=time();
        $newOrder->play_status=OrderTempModel::play_status_weizhifu;
        $newOrder->money=$data['money'];
        $newOrder->ip=Fun::Ip();
        $newOrder->ua=Fun::UA();
        $newOrder->uid=OA::$user->getId();
        return $newOrder->save();


        /*
        if(OrderTempModel::updateOrCreate(
            ['bale' => $data['bale'],'fid'=>$data['fid']],
            ['cid'=>$data['cid'],'status'=>1,'out_trade_no'=>$data['out_trade_no'],'created_at'=>time(),'updated_at'=>time()]
        )){
            return true;
        }else{
            return false;
        }*/
    }
}
